package edu.sctu.liangyuxiang.day20150623;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.*;

/**
 * Created by user20 on 2015/6/23.
 */
public class JsonUntil {

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    CloseableHttpClient closeableHttpClient = httpClientBuilder.build();

    public String getJson(String URL) throws Exception{
        HttpGet httpGet = new HttpGet(URL);
        HttpResponse httpResponse = closeableHttpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        InputStream inputStream = httpEntity.getContent();
        int count = 0;
        String string = "";
        byte[] buffer = new byte[1024];
        while ( (count=inputStream.read(buffer))!=-1) {
            string += new String(buffer, 0, count, "utf-8");
        }
        httpGet.getMethod();
        inputStream.close();

        return string;
    }

    public JsonData JsonUntil(String json){

        JSONObject jsonObject = JSONObject.parseObject(json);
        JsonData jsonData = new JsonData();

        jsonData.error = jsonObject.getInteger("error");
        jsonData.count = jsonObject.getString("count");
        jsonData.message = jsonObject.getString("message");
        jsonData.page = jsonObject.getInteger("page");
        jsonData.size = jsonObject.getInteger("size");

        JSONArray list = jsonObject.getJSONArray("list");

        for (int i = 0; i <list.size() ; i++) {
            Message message = new Message();
            String x = list.getString(i);
            JSONObject jsonObject1 = JSONObject.parseObject(x);
            message.goods_id = jsonObject1.getString("goods_id");
            message.goods_name = jsonObject1.getString("goods_name");
            message.goods_price = jsonObject1.getString("goods_price");

            jsonData.list.add(message);
        }
//        serializableMessage(jsonData);
        return jsonData;
    }

    public JsonData fastJson(String json){
        JsonData jsonData = JSON.parseObject(json, JsonData.class);
        return jsonData;
    }

//    public void serializableMessage(JsonData jsonData)throws Exception{
//        ObjectOutputStream jsons = new ObjectOutputStream(new FileOutputStream(new File("D:/message.txt")));
//        jsons.writeObject(jsonData);
//        jsons.close();
//    }
}
